import { useRef, useEffect, useState } from 'react'
/**
 *
 * @param {*} initCount 倒计时几秒
 * @param {*} callBack 倒计时归零时，要做的事
 * @returns { count, start }
 *            count: 会自动-- 的数值
 *            start: 启动倒计时的方法
 */
export default function useCountDown (initCount = 10, callBack = () => {}) {
  const timeId = useRef(null)

  const [count, setCount] = useState(initCount)

  // 启动倒计时
  const start = () => {
    setCount(initCount)

    timeId.current = setInterval(() => {
      setCount((count) => count - 1)
    }, 1000)
  }

  useEffect(() => {
    // 清理副作用函数
    return () => {
      console.log('..........')
      clearInterval(timeId.current)
    }
  }, [])

  useEffect(
    () => {
      console.log(count, timeId.current)
      // 时间到了
      if (count === 0) {
        clearInterval(timeId.current)
        callBack()
      }
    },
    [count, callBack]
  )

  return { count, start }
}
